/**
 * Usage
 *
 * 1. 点击事件
  v-analytics.click="{
    action: 'action',
    category: 'category',
    label: 'label',
    callback: () => {},
  }"
  * @params
  * callback: 向ga发送完数据之后的回调
  *
  *
 *2. PV统计  v-analytics.pageview
 *
 */

// 如果所返回的函数在超时时限以内（默认的超时时限为一秒）得到调用，该函数将清除超时事件并调用输入的函数。
// 如果所返回的函数在超时时限以内未得到调用，则无条件调用输入的函数。
function createFunctionWithTimeout(callback = () => {}, timeout) {
  let called = false

  function fn() {
    if (!called) {
      called = true
      callback()
    }
  }
  setTimeout(fn, timeout || 1000)
  return fn
}

export function analyticsFn(options = {}) {
  const channel = sessionStorage.channel ? ` ${sessionStorage.channel}` : ''

  ga('send', {
    hitType: 'event',
    eventCategory: options.category + channel,
    eventAction: options.action,
    eventLabel: options.label,
    hitCallback: createFunctionWithTimeout(options.callback),
  })
}

/* global ga */
export const analytics = {
  bind(el, binding) {
    const channel = sessionStorage.channel ? ` ${sessionStorage.channel}` : ''

    if (binding.modifiers.pageview) {
      setTimeout(() => {
        ga('send', {
          hitType: 'pageview',
          page: location.href,
          title: (binding.value && binding.value.title + channel) || document.title + channel,
        })
      }, 50)
    }

    if (binding.modifiers.click) {
      const { value } = binding
      el.addEventListener('click', (e) => {
        e.stopPropagation()
        e.preventDefault()

        if (!value) {
          throw new Error('value is required')
        }

        if (value.category) {
          ga('send', {
            hitType: 'event',
            eventCategory: value.category + channel,
            eventAction: value.action,
            eventLabel: value.label,
            hitCallback: createFunctionWithTimeout(value.callback),
          })
        }
      })
    }
  },
}
